package com.scs.application.modules.dept.controller;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.scs.application.core.exception.BusinessException;
import com.scs.application.core.mvc.controller.FlowController;
import com.scs.application.core.query.QueryContext;
import com.scs.application.core.query.QueryContextHolder;
import com.scs.application.core.utils.BeanUtils;
import com.scs.application.core.utils.StringUtils;
import com.scs.application.modules.base.entity.Patient;
import com.scs.application.modules.base.service.PatientService;
import com.scs.application.modules.cfg.utils.ParameterUtils;
import com.scs.application.modules.dept.dto.PrintDataDtlOprtUse;
import com.scs.application.modules.dept.dto.PrintDataMainOprtUse;
import com.scs.application.modules.dept.entity.OprtUse;
import com.scs.application.modules.dept.entity.OprtUseItem;
import com.scs.application.modules.dept.entity.UseMergeDtl;
import com.scs.application.modules.dept.service.OprtUseItemService;
import com.scs.application.modules.dept.service.OprtUseService;
import com.scs.application.modules.dept.service.UseMergeDtlService;
import com.scs.application.modules.sys.enums.DictTypeList;
import com.scs.application.modules.sys.model.PageResult;
import com.scs.application.modules.sys.model.RestResult;
import com.scs.application.modules.sys.service.impl.DictDataServiceImpl;
import com.scs.application.modules.thirdparty.request.view.his.HisReqServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 */
@RestController
@RequestMapping("/dept/oprt_use")
public class OprtUseController extends FlowController<OprtUseService, OprtUse> {
    @Autowired
    private UseMergeDtlService useMergeDtlService;
    @Autowired
    private OprtUseItemService oprtUseItemService;
    @Autowired
    @Lazy
    private PatientService patientService;
    @Autowired
    @Lazy
    private DictDataServiceImpl dictDataService;
    @Autowired
    HisReqServiceImpl hisReqViewService;

    @PostMapping("/updateInfo")
    public RestResult getDeptUse(@RequestBody Map para) {
        String busKey = para.get("busKey").toString();
        return RestResult.ok("ok",service.updateInfo(busKey));
    }

    @PostMapping("/toRedById")
    public RestResult toRedById(@RequestBody Map para ){
        String oprtUseId = para.get("id").toString();
        RestResult result = service.toRedById(oprtUseId);
        return result;
    }

    /**
     * 获取数据列表
     */
    @GetMapping("/pageForMerge")
    public PageResult pageForMerge() {
        QueryContext queryContext = QueryContextHolder.currentContext();

        List<UseMergeDtl> useMergeDtlList = useMergeDtlService.list();
        List<String> oprtUseIitemIds = useMergeDtlList.stream().map(o -> o.getRefId()).collect(Collectors.toList());

        // 排除已合并的消耗单
        List<String> excludeIds = Lists.newArrayList();
        if (!oprtUseIitemIds.isEmpty()) {
            List<OprtUseItem> oprtUseItems = oprtUseItemService.list(Wrappers.<OprtUseItem>query().in("id", oprtUseIitemIds));
            Map<String, List<OprtUseItem>> oprtUseItemMap = oprtUseItems.stream().collect(Collectors.groupingBy(OprtUseItem::getDeptOprtUseId));

            for (String s : oprtUseItemMap.keySet()) {
                List<OprtUseItem> oprtUseItemList = oprtUseItemService.list(Wrappers.<OprtUseItem>query().eq("dept_oprt_use_id", s));
                int allNum = oprtUseItemList.size();
                int mergeNum = oprtUseItemMap.get(s).size();
                if (allNum == mergeNum) {
                    excludeIds.add(s);
                }
            }
        }

        IPage pageResult = service.page(queryContext.getPage(),Wrappers.<OprtUse>query()
                .eq("flow_status","end").eq("flag_use_red_type","0").notIn(!excludeIds.isEmpty(),"id", excludeIds ));
        return PageResult.ok("查询成功", pageResult.getRecords(), pageResult.getTotal());
    }

    /**
     * 查询手术单进行合单
     */
    @GetMapping("/pageForSelect")
    public PageResult pageForSelect(@RequestParam Map<String, Object> reqData) {
        QueryContext queryContext = QueryContextHolder.currentContext();
        Map<String, Object> userParam =null;
        //固定参数
        if(reqData.containsKey("userParam")){
            JSONObject ob = JSON.parseObject(reqData.get("userParam")+"");
            userParam= Maps.newHashMap(ob);
        }


        IPage pageResult = service.pageForSelect(queryContext,userParam);
        return PageResult.ok("查询成功", pageResult.getRecords(), pageResult.getTotal());
    }
    /**
     * 科室审核数据更新
     *
     * @return
     */
    @PostMapping("/auditDeptOprtUse")
    public RestResult auditDeptOprtUse(@RequestBody @Valid List<String> idList) {
        service.auditDeptOprtUse(idList);
        return RestResult.ok("科室审核成功");
    }

    /**
     * @Description：顶部合计覆盖
     * @Author wyt
     * @Date 2022/3/25
     */
    @GetMapping("/sumTop")
    @Override
    public RestResult sumTop(String sumFields) {
        QueryContext queryContext = QueryContextHolder.currentContext();
        queryContext.getWrapper().getExpression().getOrderBy().clear();
        return RestResult.ok("查询成功", service.getMap(queryContext.getWrapper().select(" sum( case flag_use_red_type when 1 then abs(amount)*-1 else amount end ) as amount")));
    }

    /**
     * @Description：获取打印数据-根据供应商分单
     * @Date 2023-11-05
     * @param  id 主表主键
    */
 /*   @GetMapping(value = "/getPrintData/{id}")
    public RestResult getPrintData(@PathVariable String id) {
        OprtUse oprtUse = service.getById(id);
        BusinessException.throwErrorIf(ObjectUtil.isNull(oprtUse), "未找到主单据，不存在或者已被删除");
        List<OprtUseItem> oprtUseItemList = oprtUseItemService.list(Wrappers.<OprtUseItem>query().eq("dept_oprt_use_id",id));
        BusinessException.throwErrorIf(ObjectUtil.isNull(oprtUse), "没有相关明细数据，不需要打印");
        PrintDataMainOprtUse dataMain;
        PrintDataDtlOprtUse dataDtl;
        List<PrintDataDtlOprtUse> dataDtlList;

        // 根据供应商分组
        Map<String,List<OprtUseItem>> itemGroupSp = oprtUseItemList.stream().collect(Collectors.groupingBy(OprtUseItem::getSupplierId));
        Patient patient = null;
        if (StringUtils.isNotBlank(oprtUse.getPatientId())) {
            if (ParameterUtils.isPatientSelectHisView()) {
                patient = hisReqViewService.patientGetById(oprtUse.getPatientId());
            } else {
                patient = patientService.getById(oprtUse.getPatientId());
            }
        }

        OprtUseItem itemOne ;
        List<PrintDataMainOprtUse> mainList = new ArrayList<>();
        for(String spId: itemGroupSp.keySet()) {
            itemOne = itemGroupSp.get(spId).get(0);
            dataMain = new PrintDataMainOprtUse();
            dataDtlList = new ArrayList<PrintDataDtlOprtUse>();
            BeanUtils.copyProperties(oprtUse,dataMain);
            if (oprtUse.getPatientAge() != null && oprtUse.getPatientAge() > 0) {
                dataMain.setPatientAge(oprtUse.getPatientAge() + "");
            }else {
                dataMain.setPatientAge("");
            }
            if (patient != null && patient.getAge() != null && patient.getAge() > 0) {
                dataMain.setPatientAge(patient.getAge() +"");
            }

            dataMain.setPatientSex("").setSupplierName(itemOne.getSupplierName());
            if (patient != null && StringUtils.isNotBlank(patient.getGender())) {
                dataMain.setPatientSex(dictDataService.getLabelByValue(DictTypeList.COMMON_GENDER,patient.getGender()));
            }

            for(OprtUseItem item: itemGroupSp.get(spId)) {
                dataDtl = new PrintDataDtlOprtUse();
                BeanUtils.copyProperties(item,dataDtl);
                dataDtlList.add(dataDtl);
            }
            dataMain.setDtlList(dataDtlList);
            mainList.add(dataMain);
        }

        return RestResult.ok("操作成功",  mainList);
    }*/

    /**
     * @Description：获取打印数据-不分单
     * @Date 2023-11-05
     * @param  id 主表主键
    */
    @GetMapping(value = "/getPrintData/{id}")
    public RestResult getPrintData(@PathVariable String id) {
        OprtUse oprtUse = service.getById(id);
        BusinessException.throwErrorIf(ObjectUtil.isNull(oprtUse), "未找到主单据，不存在或者已被删除");
        List<OprtUseItem> oprtUseItemList = oprtUseItemService.list(Wrappers.<OprtUseItem>query().eq("dept_oprt_use_id",id));
        BusinessException.throwErrorIf(ObjectUtil.isNull(oprtUse), "没有相关明细数据，不需要打印");
        PrintDataMainOprtUse dataMain;
        PrintDataDtlOprtUse dataDtl;
        List<PrintDataDtlOprtUse> dataDtlList;
        Patient patient = null;
        if (StringUtils.isNotBlank(oprtUse.getPatientId())) {
            if (ParameterUtils.isPatientSelectHisView()) {
                patient = hisReqViewService.patientGetById(oprtUse.getPatientId());
            } else {
                patient = patientService.getById(oprtUse.getPatientId());
            }
        }

        List<PrintDataMainOprtUse> mainList = new ArrayList<>();

        dataMain = new PrintDataMainOprtUse();
        dataDtlList = new ArrayList<PrintDataDtlOprtUse>();
        BeanUtils.copyProperties(oprtUse,dataMain);
        if (oprtUse.getPatientAge() != null && oprtUse.getPatientAge() > 0) {
            dataMain.setPatientAge(oprtUse.getPatientAge() + "");
        }else {
            dataMain.setPatientAge("");
        }
        if (patient != null && patient.getAge() != null && patient.getAge() > 0) {
            dataMain.setPatientAge(patient.getAge() +"");
        }

        dataMain.setPatientSex("");
        if (patient != null && StringUtils.isNotBlank(patient.getGender())) {
            dataMain.setPatientSex(dictDataService.getLabelByValue(DictTypeList.COMMON_GENDER,patient.getGender()));
        }

        for(OprtUseItem item: oprtUseItemList) {
            dataDtl = new PrintDataDtlOprtUse();
            BeanUtils.copyProperties(item,dataDtl);
            dataDtlList.add(dataDtl);
        }
        dataMain.setDtlList(dataDtlList);
        mainList.add(dataMain);

        return RestResult.ok("操作成功",  mainList);
    }


    private void fillEntity(OprtUse entity) {
        entity.setCountDtl(oprtUseItemService.count(Wrappers.<OprtUseItem>query().select("id").eq("dept_oprt_use_id",entity.getId())));
    }

    /**
     * 根据ID查找数据
     */
    @GetMapping("/find")
    public RestResult find(@RequestParam("id") Serializable id) {
        OprtUse entity = service.getById(id);
        if (entity == null) {
            return RestResult.error("数据查询失败<br>可能所操作数据已被删除，请刷新后重新尝试操作");
        }
        fillEntity(entity);

        return RestResult.ok("获取数据成功", entity);
    }

    /**
     * 添加/更新数据
     */
    @PostMapping("/save")
    public RestResult saveItem(@Valid @RequestBody OprtUse entity) {
        boolean isOk = service.saveOrUpdate(entity);
        if (!isOk) {
            return RestResult.error("数据保存失败");
        }
        fillEntity(entity);
        return RestResult.ok("数据保存成功", entity);
    }
}
